<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form
          @submit.native.prevent
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="用户名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入用户名称"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phone">
            <el-input
              v-model="queryParams.phone"
              placeholder="请输入手机号码"
              clearable
              style="width: 240px"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['system:user:export']"
              >批量导出</el-button
            >
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column label="编号" align="center" type="index" />
          <el-table-column
            label="头像"
            align="center"
            key="gender"
            prop="photo"
          >
            <template #default="scope">
              <el-avatar :size="50" :src="scope.row.photo"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center" key="name" prop="name" />
          <el-table-column
            label="性别"
            align="center"
            key="gender"
            prop="gender"
          >
            <template #default="scope">
              {{ scope.row.gender == "MALE" ? "男" : "女" }}
            </template>
          </el-table-column>
          <el-table-column
            label="手机号码"
            align="center"
            key="phone"
            prop="phone"
            width="120"
          />
          <el-table-column
            label="关系"
            align="center"
            key="relation"
            prop="relation"
          >
            <template #default="scope">
              {{ relationObj[scope.row.relation] }}
            </template>
          </el-table-column>
          <el-table-column
            label="籍贯"
            align="center"
            key="nativePlace"
            prop="nativePlace"
          />
          <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :options="sys_notice_status" :value="scope.row.status" />
        </template>
      </el-table-column>
          <el-table-column
            label="生日"
            align="center"
            key="birthDate"
            prop="birthDate"
          />
          <el-table-column
            label="去世时间"
            align="center"
            key="deathDate"
            prop="deathDate"
          />
          <el-table-column
            label="描述"
            align="center"
            key="description"
            prop="description"
            :show-overflow-tooltip="true"
          />

          <!-- <el-table-column
              label="纪念馆 "
              align="center"
              prop="createTime"
              width="170"
            >
              <template #default="scope">
                <span>{{ parseTime(scope.row.gmtCreate) }}</span>
              </template>
            </el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            width="210"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <a
                href="javascript:;"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleUpdate(scope.row, 1)"
                >查看</a
              >
              <a
                href="javascript:;"
                style="
                  color: #358de5;
                  text-decoration: none;
                  margin-right: 10px;
                "
                @click="handleUpdate(scope.row, 2)"
                >编辑</a
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form
        @submit.native.prevent
        :model="form"
        :rules="rules"
        ref="userRef"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="头像" prop="photo">
              <el-upload
                ref="uploadRef"
                :action="baseUrl + '/oss/upload'"
                :headers="headers"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="handleAvatarSuccess"
              >
                <el-avatar :size="80" :src="form.photo"></el-avatar>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户生日" prop="birthDate">
              <el-date-picker
                v-model="form.birthDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in sys_notice_status"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="去世时间" prop="deathDate">
              <el-date-picker
                v-model="form.deathDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option
                  v-for="dict in sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关系：" label-width="120">{{
              relationObj[form.relation]
            }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="nativePlace" class="form-item">
              <el-input
                v-model="form.nativePlace"
                placeholder="请输入"
                maxlength="10"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述">
              <el-input
                v-model="form.description"
                type="textarea"
                placeholder="请输入内容"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer v-if="title !== '详情'">
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script setup name="User">
import {
  queryFamilytreePage,
  editFamilytree,
  familytreeExport,
} from "@/api/familyTree";
import { getToken } from "@/utils/auth";
const route = useRoute();
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const headers = ref({ Authorization: "Bearer " + getToken() });
const { proxy } = getCurrentInstance();
//家属关系
const relationObj = ref({
  FATHER: "父亲",
  MOTHER: "母亲",
  HUSBAND: "丈夫",
  WIFE: "妻子",
  BROTHER: "兄弟",
  SISTER: "姐妹",
  SON: "儿子",
  DAUGHTER: "女儿",
  SELF: "本人",
  UNKNOWN: "其他",
});


const sys_notice_status = [
  {
    label: "建在",
    value: "ALIVE",
  },
  {
    label: "已故",
    value: "DEAD",
  },
];
const sys_user_sex = [
  {
    label: "男",
    value: "MALE",
  },
  {
    label: "女",
    value: "FEMALE",
  },
];
const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {
    id: undefined,
    name: undefined,
    status: undefined,
    nativePlace: undefined,
    phone: undefined,
    birthDate: undefined,
    gender: undefined,
    photo: undefined,
    deathDate: undefined,
    description:undefined
  },
  queryParams: {
    pageNum: 1,
    pageSize: 1000,
    name: undefined,
    phone: undefined,
    creatorId: route.params.userId,
  },
  rules: {
    name: [
      { required: true, message: "用户名称不能为空", trigger: "blur" },
      {
        min: 2,
        max: 20,
        message: "用户名称长度必须介于 2 和 20 之间",
        trigger: "blur",
      },
    ],
    phone: [
      {
        required: true,
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户列表 */
const getList = () => {
  loading.value = true;
  queryFamilytreePage({
    ...queryParams.value,
  }).then((res) => {
    loading.value = false;
    userList.value = res.rows;
    total.value = Number(res.total);
  });
};

/** 头像上传 */
const handleAvatarSuccess = (res, file) => {
  form.value.photo = res.url;
};

const beforeAvatarUpload = (file) => {
  const isFileType = ["image/jpeg", "image/png"].indexOf(file.type) < 0;
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (isFileType) {
    ElMessage.error("上传头像图片格式不正确!");
  }

  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return !isFileType && isLt2M;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.value = {
    pageNum: 1,
    size: 10,
    name: undefined,
    phone: undefined,
    creatorId: route.params.userId,
  };
  handleQuery();
};

/** 导出按钮操作 */
const handleExport = async () => {
  proxy.$modal.loading("文件导出中，请稍候...");
  let result = await familytreeExport();
  const blob = new Blob([result]);
  let link = document.createElement("a");
  link.href = URL.createObjectURL(blob);
  link.download = "用户列表_" + new Date().getTime() + ".xlsx";
  link.click();
  proxy.$modal.closeLoading();
};

/** 选择条数  */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.userId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 重置操作表单 */
const reset = () => {
  form.value = {
    id: undefined,
    name: undefined,
    status: undefined,
    nativePlace: undefined,
    phone: undefined,
    birthDate: undefined,
    gender: undefined,
    photo: undefined,
    deathDate: undefined,
    description:undefined
  };
  proxy.resetForm("userRef");
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  changeScore.value = false;
  reset();
};

/** 修改按钮操作 */
const handleUpdate = (row, type) => {
  reset();
  title.value = type == 1 ? "详情" : "编辑";
  form.value = {
    ...row,
  };
  open.value = true;
};

/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["userRef"].validate((valid) => {
    if (valid) {
      editFamilytree(form.value).then((response) => {
        proxy.$modal.msgSuccess("编辑成功");
        open.value = false;
        getList();
      });
    }
  });
};

getList();
</script>
  <style lang='scss' scoped>
</style>
  